<?php
// +----------------------------------------------------------------------
// | APP版本
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------
namespace app\event\app;

use app\common\event\Base;
use app\event\ucenter\User as UserEvent;
use app\model\app\CtripOrder as CtripOrderModel;
use app\model\app\JdGood as JdGoodModel;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\model\ucenter\UserTask as UserTaskModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\helper\Str;

class Ctrip extends Base
{


    public $domain = 'https://m.ctrip.com/restapi/soa2/14984/json/getAllianceOrderList';//

    protected $status_arr = ['已成交'=>2];
    protected $type_arr = ' [
        {
            "name": "国内玩乐",
            "value": "ACT"
        },
        {
            "name": "海外玩乐",
            "value": "EACT"
        },
        {
            "name": "汽车票",
            "value": "BUS"
        },
        {
            "name": "国内用车",
            "value": "CAR"
        },
        {
            "name": "一元众筹（下线）",
            "value": "CDF"
        },
        {
            "name": "游轮",
            "value": "CRU"
        },
        {
            "name": "包团定制",
            "value": "CUS"
        },
        {
            "name": "自由行",
            "value": "DIY"
        },
        {
            "name": "机票",
            "value": "FLT"
        },
        {
            "name": "名店购(到店购)",
            "value": "FSI"
        },
        {
            "name": "外币兑换",
            "value": "FSS"
        },
        {
            "name": "国际专车",
            "value": "GJC"
        },
        {
            "name": "团购",
            "value": "GRP"
        },
        {
            "name": "酒店",
            "value": "HTL"
        },
        {
            "name": "酒店（预付）",
            "value": "HTLPP"
        },
        {
            "name": "优品商城",
            "value": "MAL"
        },
        {
            "name": "会场",
            "value": "MTG"
        },
        {
            "name": "度假",
            "value": "PKG"
        },
        {
            "name": "景+酒",
            "value": "SHX"
        },
        {
            "name": "超级会员",
            "value": "SPR"
        },
        {
            "name": "场馆预定",
            "value": "SPT"
        },
        {
            "name": "国内门票",
            "value": "TIC"
        },
        {
            "name": "海外门票",
            "value": "ETIC"
        },
        {
            "name": "跟团游",
            "value": "TOU"
        },
        {
            "name": "火车票",
            "value": "TRN"
        },
        {
            "name": "租车",
            "value": "ZCC"
        },
        {
            "name": "酒店预售",
            "value": "HTLYS"
        },
        {
            "name": "民宿",
            "value": "BNB"
        },
        {
            "name": "国际租车",
            "value": "EZCC"
        },
        {
            "name": "会员商城",
            "value": "FSO"
        },
        {
            "name": "海外预售",
            "value": "EGRP"
        },
        {
            "name": "酒店",
            "value": "HOTEL"
        },
        {
            "name": "美食林",
            "value": "FOD"
        },
        {
            "name": "乐高",
            "value": "AOS"
        },
        {
            "name": "核酸",
            "value": "HSJ"
        },
        {
            "name": "向导",
            "value": "GUI"
        },
        {
            "name": "欧铁",
            "value": "EUR"
        },
        {
            "name": "权益",
            "value": "RIGHT"
        },
        {
            "name": "出行服务",
            "value": "FLTX"
        },
        {
            "name": "机票预售",
            "value": "PRESALE"
        },
        {
            "name": "酒店（日历房套餐）",
            "value": "HTLR"
        },
        {
            "name": "酒店（月租房）",
            "value": "HTLM"
        },
        {
            "name": "旅游预售",
            "value": "TOUR_PRESALE"
        },
        {
            "name": "展演日历套",
            "value": "EXH"
        },
        {
            "name": "邮轮预售",
            "value": "CUP"
        }
    ]';
    public function curl($sysParams)
    {
        $cookie = 'GUID=09031040214795419564; nfes_isSupportWebP=1; UBT_VID=1737509555517.66fcxEz4l5LJ; _RF1=2408%3A8220%3A344%3Aacc0%3A6ccd%3Ab545%3A1e06%3A8f61; _RSG=hnqjBE8Dx0ANIe0ia2tfuB; _RDG=28cf7b81567f72264e2e553c9e35e54ab0; _RGUID=a03b3483-8bb7-4c6b-be29-dc292c028497; Session=smartlinkcode=U130026&smartlinklanguage=zh&SmartLinkKeyWord=&SmartLinkQuary=&SmartLinkHost=; login_type=0; ibulanguage=CN; ibulocale=zh_cn; cookiePricesDisplayed=CNY; MKT_CKID=1737512912833.sbk8w.e3e9; _ga=GA1.2.60790152.1737512917; _gid=GA1.2.1315603099.1737512917; ibu_h5_site=CN; ibu_h5_group=ctrip; ibu_h5_local=zh-cn; ibu_h5_local=zh-cn; ibu_h5_lang=zhcn; ibu_h5_curr=CNY; Hm_lvt_37b54c42b9dde393e60c88c1a84657cb=1737514242; Hm_lpvt_37b54c42b9dde393e60c88c1a84657cb=1737514242; HMACCOUNT=3900DEB2415B5BB9; Hm_lvt_576acc2e13e286aa1847d8280cd967a5=1737514395; Hm_lpvt_576acc2e13e286aa1847d8280cd967a5=1737514395; Hm_lvt_77b03ea75ddaa8a6bf817822b2af25f1=1737514400; Hm_lpvt_77b03ea75ddaa8a6bf817822b2af25f1=1737514578; Hm_lvt_a8d6737197d542432f4ff4abc6e06384=1737524884; Hm_lpvt_a8d6737197d542432f4ff4abc6e06384=1737524884; HMACCOUNT=3900DEB2415B5BB9; _jzqco=%7C%7C%7C%7C%7C1.7522607.1737512912775.1737512912775.1737524884326.1737512912775.1737524884326.0.0.0.2.2; _ga_5DVRDQD429=GS1.2.1737537466.2.1.1737537469.0.0.0; _ga_B77BES1Z8Z=GS1.2.1737537466.2.1.1737537469.57.0.0; MKT_Pagesource=H5; tangram_city_id=2; tangram_district_id=157; cticket=939ED63C6AC93155B00179778C4AE7D5EF6D8F7F496BB59673D9BF426BD9E2EC; login_uid=2FA226EA1758F92D3029BD69FF63A305; DUID=u=5F403D5B5F689024515F5EEC3ED778A4&v=0; AHeadUserInfo=VipGrade=0&VipGradeName=%C6%D5%CD%A8%BB%E1%D4%B1&UserName=&NoReadMessageCount=0; _PRO_sso_lat_assertion_=52574340b6db869cbeb0c104842675901a24566c8ea084869d2ce50172162f127a08cc6af4e16650b8a1c9bcfbbdd3ccafba97fefe4e05881fa52bb650aea2d296fa9ec327a5978fe46b5bde3b86d0096b4af3d4a7a1b3c26729fddddba28b064616b0fc365db0a1a873fd86104358b704a2ed327170c60af6bdf7738690b498; _PRO_sso_lat_assertion_signature_=81f059af8023ea3c542aa2ccd891a8bfc8ae74a6005eede013e344e6991db6e974e05ffa2dab53f5c45abf197a241e4567bcc19a0b9fbb4790e1f4cc15306e9a9813f7ba62881cb8f268e694203066d08ff009b5fa62823b3d29b5e3ddef1cbe2e1979df7fd886128c391af204693adba605e16ce253d95954c3b16ef55d6349; set_parentAllianceID=; environmentFrom=; envP=; atype=; _ubtstatus=%7B%22vid%22%3A%221737509555517.66fcxEz4l5LJ%22%2C%22sid%22%3A4%2C%22pvid%22%3A46%2C%22pid%22%3A%2210650006882%22%7D; union_ticket=eyJpc0xvZ2luIjp0cnVlLCJpc0FjdGl2YXRlIjp0cnVlfQ%3D%3D; _lizard_LZ=FEfs-v1noz5xh7UleScM8WKVZ2uP3YDCTNBAiIOdkwyQ4GjHpb+JqLRXrag90mt6; savePosition=0; _resDomain=https%3A%2F%2Fws-s.tripcdn.cn; _pd=%7B%22_o%22%3A11%2C%22s%22%3A19%2C%22_s%22%3A0%7D; Union=OUID=H5B2Bonline&AllianceID=5898222&SID=163951586&SourceID=2055&createtime=1737539783&Expires=1738144583396; MKT_OrderClick=ASID=5898222163951586&AID=5898222&CSID=163951586&OUID=H5B2Bonline&CT=1737539783397&CURL=https%3A%2F%2Fcontents.ctrip.com%2Fbuildingblocksweb%2Fspecial%2Fmembershipcard%2Findex.html%3F%26allianceid%3D5898222%26sid%3D163951586%26ouid%3DH5B2Bonline%26sourceid%3D2055%26Popup%3Dclose%26openapp%3D3&VAL={"pc_vid":"1737509555517.66fcxEz4l5LJ"}; _bfa=1.1737509555517.66fcxEz4l5LJ.1.1737539925686.1737539931530.4.87.10650046616';
        $headerArray = array("Content-type:application/json;charset='utf-8'",
            "Accept:application/json", "Platform:pc", 'Content-Length: ' . strlen($sysParams));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->domain);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $sysParams);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);

        $response = curl_exec($ch);
        curl_close($ch);
// 处理响应数据
        $response_data = json_decode($response, true);
        return $response_data['allianceOrderList'];
    }

    public function getOrder($time)
    {
//        "orderStatus": "S",已成交
//        "paystatus": "F",,奖励计算中
        try {
//            "orderId": "1128134402645263",
//            "productName": "濮阳东-郑州东",
//            "productType": "TRN",
//            "productTypeName": "火车票",
//            "orderAmount": 116.0000,
//            "commission": 0.0000,
//            "commissionRate": 0.0000,
//            "commissionFlag": 0,
//            "orderStatus": "S",
//            "orderDate": "2025-01-22 16:12:47",
//            "etd": "2025-01-22 16:12:47",
//            "commissionDate": "",
//            "returnDate": "",
//            "adjustDate": "",
//            "validAmountRemark": "",
//            "remark": "",
//            "paystatus": "F",
//            "productId": 0,
//            "orderSource": 1,
//            "isSettlemented": 0,
//            "isGrpMultiCouponOrder": 0,
//            "couponCount": 0,
//            "waitSettlementCouponCount": 0


//            "orderId": 1128134402645263,
//            "productName": "濮阳东-郑州东",
//            "orderDate": "2025-01-22 16:12:47",
//            "businessType": "火车票",
//            "quantity": 1,
//            "amount": 116.0000,
//            "orderStatus": "已成交",
//            "aid": 5898222,
//            "sid": 163951586,
//            "ouid": "kfptpctool01",
//            "validAmount": 0.0000,
//            "etd": "",
//            "remark": "",
//            "estimateCommission": "0",
//            "commission": "暂无",
//            "orderType": "常规推广"
            $param = '{"pageIndex":1,"pageSize":10,"orderId":null,"sid":null,"beginDate":"' . time_format($time - 86400 * 10, 'Y-m-d') . '","endDate":"' . time_format($time + 86400, 'Y-m-d') . '","dealBeginTime":null,"dealEndTime":null,"businessType":"ALL","orderStatus":"ALL","tag":"","environmentFrom":"","orderType":"ALL","clientFrom":"PC"}';
            $orders = $this->curl($param);
            dump($orders);
            foreach ($orders as $order) {
                $this->_sysnOrder($order);
            }
            $result = ['code' => 0, 'data' => count($orders)];
        } catch (\Exception $e) {
            // 回滚事务
            $result = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $result;


    }

    private function _sysnOrder($trades)
    {
        $trade = [];
        foreach ($trades as $index_g => $item) {
            $trade[Str::snake($index_g)] = $item;
        }
        dump($trade);
        unset($trade['aid']);
        unset($trade['sid']);
        if (!empty($trade['order_date'])) {
            $trade['create_time'] = $trade['order_date'];
            unset($trade['order_date']);
        }
        $trade['order_status'] = $this->status_arr[$trade['order_status']];
        if ($trade['commission'] == '暂无') {
            $trade['commission'] = 0;
        }
        $order = CtripOrderModel::where('order_id', $trade['order_id'])->find();

        if (!$order) {
            $order = CtripOrderModel::create($trade);
            if (!empty($order['ouid'])) {
//                $user = UserModel::where('id', explode('_', $order['ouid'])[1])->find();
                $user = UserModel::where('id', 16006)->find();
                if ($user) {
                    $order['user_id'] = $user['id'];
                    $order->save();
                    $userTask = $this->_bindTask($order, $user);
                    $this->_payFee($userTask);
                }
            }

        } else {

            if ($trade['order_status'] != $order['order_status']) {
                $order->save($trade);
                // 退款订单
                if ($order['user_id']) {
                    $user = UserModel::where('id', $order['user_id'])->find();
                    if ($user) {
                        $userTask = UserTaskModel::where('user_id', $user['id'])
                            ->where('task_id', 11)
                            ->where('task_type', 23)
                            ->where('relation_id', $order['id'])
                            ->find();
                        if ($userTask) {
                            $userTask['step'] = $order['order_status'];
                            $userTask['submit_info'] = $order->toArray();
                            $userTask->save();
                            $this->_payFee($userTask);
                        }
                    }
                }
            }

        }
    }

    public function test1()
    {

        $domain = 'https://api.jd.com/routerjson';
        //组装系统参数
        $sysParams['app_key'] = $this->appKey;
        $sysParams['format'] = 'json';
        $sysParams['sign_method'] = 'md5';
        $sysParams['v'] = '1.0';
        $sysParams['method'] = 'jd.union.open.goods.jingfen.query';
//        $sysParams['timestamp'] = date("Y-m-d H:i:s").'.000'.$this->getStandardOffsetUTC(date_default_timezone_get());;
        $sysParams['timestamp'] = date("Y-m-d H:i:s");

        //$sysParams["access_token"] = $access_token;

        $sysParams[$this->json_param_key]['goodsReq']['eliteId'] = 1;
//        $sysParams[$this->json_param_key]['goodsReqDTO']['keyword'] = '鞋子';
//        $sysParams[$this->json_param_key]['orderReq']['startTime'] = '2024-12-09 16:11:01';
//        $sysParams[$this->json_param_key]['orderReq']['startTime'] = '2024-12-09+16:51:01';
//        $sysParams[$this->json_param_key] = json_encode($sysParams[$this->json_param_key]);
        //签名
        $sysParams["sign"] = $this->generateSign($sysParams);


        $re = $this->curl($domain, $sysParams);
        dump(json_decode($re, true));
        dump($sysParams);
        exit();


    }


    private function _bindTask($order, $user)
    {
        // 新增任务
        $userTask['task_id'] = 4;
        $userTask['relation_id'] = $order['id'];
        $userTask['task_type'] = 29;
        $userTask['user_id'] = $user['id'];
        $userTask['agent_id'] = $user['agent_id'];
        $userTask['title'] = $order['business_type'];
        $userTask['money'] = $order['amount'];
        $userTask['commission'] = $order['commission'];
        $userTask['task_no'] = $order['order_id'];
        $userTask['step'] = $order['order_status'];
        $userTask['submit_info'] = $order->toArray();
        $userTask['status'] = 1;
        $userTask = UserTaskModel::create($userTask);
        if (!$userTask) {
            throw new Exception('系统故障');
        }
        return $userTask;
    }


    protected function _payFee($userTask)
    {


        if (in_array($userTask['step'], [-1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13, 14, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31])) {
            // 订单失效。
            $userTask['status'] = 3;
        } elseif ($userTask['step'] == 15) {
            $userTask['status'] = 0;
        } elseif ($userTask['step'] == 16) {
            $userTask['status'] = 1;
        } elseif ($userTask['step'] == 17) {
            $userTask['status'] = 2;
            // 发放佣金
            $log = UserMoneyLogModel::where('user_id', $userTask['user_id'])->where('type', 53)
                ->where('order_id', $userTask['task_no'])
                ->where('channel', 'ctrip')->find();
            if (!$log && !empty($userTask['commission']) && $userTask['commission'] > 0) {
                $user = UserModel::where('id', $userTask['user_id'])->find();
                UserEvent::exhibitionIncome($user, $userTask['commission'], $userTask['title'], 53, $user['id'], $userTask['task_no'], 0, 'ctrip', 4);
            }
        } else {
            $userTask['status'] = 4;
        }

        $userTask->save();
        if ($userTask['status'] == 3 || $userTask['status'] == 4) {
            // 失败订单，查询是否扣款
            $log = UserMoneyLogModel::where('user_id', $userTask['user_id'])->where('type', 53)
                ->where('order_id', $userTask['task_no'])
                ->where('channel', 'ctrip')
                ->where('is_eversal', 0)
                ->find();
            if ($log) {
                $user = UserModel::where('id', $userTask['user_id'])->find();
                UserEvent::exhibitionIncomeBack($user, '出行返利因退款或退货返佣取消', $user['id'], $userTask['task_no'], 'ctrip', 4);
            }
        }
    }

}
